package com.zhonglian.bloodpressure.utils;

import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.WindowManager;

import com.zhonglian.bloodpressure.R;

import java.util.Date;

/**
 * Created : Yx
 * Time : 2018/11/13 15:04
 * Describe :定时任务，每隔TIME时间执行某事
 */
@SuppressLint("HandlerLeak")
public class RunService extends Service {

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private int time;//设定的时间（分钟）
    private int anHour; //记录间隔时间毫秒数（分钟毫秒数）
    private int number = 0; //记录alertdialog出现次数
    private MediaPlayer mediaPlayer = new MediaPlayer();
    private AssetFileDescriptor assetFileDescriptor;//文件
    private AlarmManager manager;//系统级别的提示服务,在特定的时刻为我们广播一个指定的Intent
    private PendingIntent pi;//待确定意图

    //保活保活
    public static final int NOTIFICATION_ID = 1234;//保活ID

    @Override
    public void onCreate() {
        super.onCreate();
        //开启保活
        //Intent ret = new Intent(this, MyJobService.class);
        //startService(ret);
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    inItMediaPlayer(1);//播放提醒
                    AlertDialog.Builder builder = new AlertDialog.Builder(RunService.this);
                    builder.setTitle("提醒");
                    builder.setMessage("血压监测" + (number - 1));
                    builder.setCancelable(false);
                    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            inItMediaPlayer(2);//继续播放无声音乐
                        }
                    });
                    final AlertDialog dialog = builder.create();
                    dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
                    dialog.show();
            }
        }
    };

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String t = intent.getStringExtra("Time");
        if (t != null && !"".equals(t)) {
            number = 0;
            time = Integer.parseInt(t);
        }
        if (time != 0) {//等于0 未开启，大于0，开启提醒
            manager = (AlarmManager) getSystemService(ALARM_SERVICE);
            anHour = time * 60 * 1000;
            Log.i("aaaa", "----Time:" + time + "----Anhour:" + anHour);
            //当前系统时间加上间隔时间等于 下次提醒时间triggerAtTime
            long triggerAtTime = SystemClock.elapsedRealtime() + anHour;
            Intent i = new Intent(this, RunReceiver.class);
            pi = PendingIntent.getBroadcast(this, 0, i, 0);
            //在triggerAtTime时间时 广播指定意图
            manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pi);
            if (number != 0) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Log.i("aaaa", "----提醒----" + new Date().toString());
                        mHandler.sendEmptyMessage(1);
                    }
                }).start();
            } else {//刚打开APP/或重新设置时间后，number等于0，播放无声音乐
                //播放器保活- 白色保活 -
                inItMediaPlayer(2);//播放无声音乐
            }
            number++;
            startNotifi(time);//开启通知栏

        } else {//time=0,不开启
            deleteNotifi();//关闭通知栏
        }
        flags = START_STICKY;
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mediaPlayer.release();//回收流媒体资源。
        manager.cancel(pi);//取消取消
        // 如果Service被杀死，干掉通知
        deleteNotifi();
    }

    /**
     * 开启通知栏
     *
     * @param t
     */
    private void startNotifi(int t) {
        //---通知栏提醒 start --白色保活--
        //实例化Notification.Builde并设置相关属性
        Notification.Builder builder = new Notification.Builder(this);
        builder.setContentTitle("动态血压检测中..."); //设置通知标题
        builder.setContentText("退出应用将停止检测!");
        builder.setContentInfo("每隔" + t + "分钟");
        builder.setSmallIcon(R.mipmap.ic_launcher);//设置小图标
        builder.setAutoCancel(true);
        builder.setWhen(System.currentTimeMillis()); //设置通知时间，默认为系统发出通知的时间，通常不用设置
        builder.setShowWhen(true);
        builder.setNumber(3);
        //通过builder.build()方法生成Notification对象,并发送通知,id=1
        startForeground(NOTIFICATION_ID, builder.build());//使用startForeground让android服务前台运行
        //启动服务去同时绑定该前台通知栏，当RunService还是在前台运行
        Intent innerIntent = new Intent(this, CancelNoticeService.class);
        innerIntent.putExtra("T", t);
        startService(innerIntent);
        //---通知栏end

    }

    /**
     * 取消通知
     */
    private void deleteNotifi() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            NotificationManager mManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            mManager.cancel(NOTIFICATION_ID);
        }
    }

    /**
     * 初始播放器
     */
    private void inItMediaPlayer(int num) {
        //打开Asset目录
        try {
            pause();//判断是否存在后，停止播放并清空（不先停止会报IllegalStateException）
            if (assetFileDescriptor != null) {
                assetFileDescriptor.close();
                assetFileDescriptor = null;
            }
            //打开音乐文件music.mp3
            if (num == 1) {
                assetFileDescriptor = getAssets().openFd("music.mp3");
            } else {
                assetFileDescriptor = getAssets().openFd("notice.mp3");
            }
            //设置媒体播放器的数据资源
            mediaPlayer.setDataSource(assetFileDescriptor.getFileDescriptor(), assetFileDescriptor.getStartOffset(), assetFileDescriptor.getLength());
            mediaPlayer.prepare();//准备
            play();//播放
        } catch (Exception e) {
            e.printStackTrace();
            Log.i("aaaa", "RunService_IOException" + e.toString());
        }
    }


    /**
     * 播放音频
     */
    private void play() {
        if (mediaPlayer != null && !mediaPlayer.isPlaying()) {
            mediaPlayer.start();//播放
            //循环播放
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer arg0) {
                    mediaPlayer.start();
                    mediaPlayer.setLooping(true);
                }
            });
        }
    }

    /**
     * 停止播放
     */
    private void pause() {
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            mediaPlayer.pause();//暂停媒体播放
            mediaPlayer.reset();//重置清空至未初始化状态。
        }
    }


}
